import config from '@/config'
import {permissionCheck,phonePermissionSetting} from '@/utils/phonePermissionCheck'

//组件内部需在methods写水印内容函数以及图片上传成功回调函数
export default {
  data() {
    return {
      windowWidth:1080,//画布宽度列表
      windowHeight:1440,//画布高度列表
      timer:[],//报错定时器id以销毁
      uploadMaskImgCanvasId: 'mycanvas'
    }
  },
  methods:{
    uploadMaskImg (params){
      this.chooseImage(params)
    },
    //选择照片
    chooseImage(params){
      const callback = ()=>{
        console.log('chooseImage', this.uploadMaskImgCanvasId)
        uni.chooseImage({
          count: 1,
          sourceType: params && params.sourceType || ["camera"],
          crop:{
            quality: 80,
            width: 1080,
            height: 1440,
          },
          success: (res) => {
            this.isUploading = true
            console.log('chooseImageSuccess', this.uploadMaskImgCanvasId)
            res.tempFilePaths.forEach( (item,index) => {
              this.getImageInfo(item, params)
            })
          },
        });
      }
      // #ifdef H5
      callback()
      // #endif

      //由于ios的机制问题，只有用过该功能它的权限列表才会出现该权限的设置,ios调用第一次就可直接打开相机
      // #ifndef H5
      const iosFirstOpenCamera = this.$store.getters.iosFirstOpenCamera
      if(uni.getSystemInfoSync().platform === 'ios' && iosFirstOpenCamera){
        this.$store.commit('SET_IOS_FIRST_OPEN_CAMERA', false)
        callback()
      }else{
        permissionCheck().then(res=>{
          callback()
        }).catch(err =>{
          uni.showModal({
            title: '手机权限',
            content: err,
            success: function (res) {
              if (res.confirm) {
                phonePermissionSetting()
              } else if (res.cancel) {
              }
            }
          });
        })
      }
      // #endif
    },

    // 获得照片信息
    getImageInfo(item, params){
      console.log('createCanvasContext', item, this.uploadMaskImgCanvasId)
      let ctx = uni.createCanvasContext(this.uploadMaskImgCanvasId || `mycanvas`, this)
      console.log('afterCreateCanvasContext', this.uploadMaskImgCanvasId)
      uni.getImageInfo({
        src: item,
        success: async image => {
          //获取图片宽高
          this.windowWidth = image.width
          this.windowHeight = image.height

          //睡眠器，强制优先执行ctx.drawImage
          await new Promise((resolve, reject) => {
            setTimeout(() => {
              ctx.drawImage(item,0,0,image.width,image.height)
              resolve()
            })
          })

          //设置画笔样式
          ctx.setFillStyle('#fff')
          ctx.lineWidth = 4;
          ctx.lineCap = "round"
          ctx.lineJoin = "round"
          ctx.setFontSize(image.width * 0.037)

          //写水印
          this.maskContent(ctx, image, params)

          //绘制图片
          this.draw(ctx, image, params)
        },
        fail: err => {
          console.log(err)
        }
      });
    },

    //写水印
    maskContent(){},

    //绘制图片
    draw(ctx, image, params){
      ctx.draw(false, this.$nextTick(()=>{
        //回调中使用setTimeout防止图片过大或者手机性能过低导致canvas没画完就导出图片报错
        this.timer.push(setTimeout(()=>{
          uni.canvasToTempFilePath({
            height: image.height,
            width: image.width,
            destHeight: image.height,
            destWidth: image.width,
            fileType: 'jpg',
            canvasId: this.uploadMaskImgCanvasId || `mycanvas`,
            success: res => {
              //上传图片
              this.upload(res.tempFilePath, res, params)
            },
            fail: function(err) {
              this.isModalShow = true
              this.modalContent = '图片上传失败'
              this.isUploading = false
            },
          },this)
        },500))
      }))
    },

    //上传图片
    upload(tempFilePaths, tempFile, params){
      const uploadTask = uni.uploadFile({
        url: config.baseUrl + '/system/oss/upload',
        filePath: tempFilePaths,
        name: 'file',
        header: {
          Authorization: 'Bearer ' + this.$store.getters.token
        },
        success: (uploadFileRes) => {
          const data = JSON.parse(uploadFileRes.data)
          //水印图片上传成功后回调函数
          this.uploadSuccessCallback(data, params)
        },
        fail: (err) => {
          this.isModalShow = true
          this.modalContent = '上传失败，图片已缓存'
          //水印图片上传网络超时回调函数
          this.uploadTimeoutCallback(tempFile, params)
        },
        complete: () => {
          this.isUploading = false
        }
      });
      setTimeout(() => {
        if(this.isUploading){
          uploadTask.abort()
        }
        this.isUploading = false
      }, 10000)
    },

    //水印图片上传成功后回调函数
    uploadSuccessCallback(){},

    //水印图片上传网络超时回调函数
    uploadTimeoutCallback(){},
  },
  beforeDestroy(){
    this.timer.forEach(item => {
      clearTimeout(item)
    })
  }
}


